// 全局变量
var today = new Date();
var todayTxt = today.format('yyyy-MM-dd');
var checkTable = void 0;

var MY_WD_PRESCRIPTION_SUPERVISION = (function() {

    function getSearchParams(){

        var data = {};

        // 日期 from - to
        var $dtFrom = $('#dtFrom');
        if ( !$dtFrom.val().length ){
            WeKnow.errorMsg('请输入查询开始日期');
            $dtFrom.focus();
            return false;
        }

        var dtFrom = $dtFrom.val();
        if ( !MY_VALIDATOR.isDate(dtFrom,'yyyy-MM-dd')){
            WeKnow.errorMsg('查询开始日期格式不正确');
            $dtFrom.focus();
            return false;
        }
        data.dtFrom = dtFrom;

        // 查询日期to
        var $dtTo = $('#dtTo');
        if ( !$dtTo.val().length ){
            WeKnow.errorMsg('请输入查询结束日期');
            $dtTo.focus();
            return false;
        }

        var dtTo = $dtTo.val();
        if ( !MY_VALIDATOR.isDate(dtTo,'yyyy-MM-dd')){
            WeKnow.errorMsg('查询结束日期格式不正确');
            $dtTo.focus();
            return false;
        }
        if($dtFrom.val()>$dtTo.val()){
            WeKnow.errorMsg('开始时间不能大于结束时间');
            return false;
        }
        data.dtTo = dtTo;

        // 诊所名
        var searchName = $.trim( $('#searchName').val());
        if ( searchName.length ){
            data.name = searchName;
        }

        //医疗机构类型
        var institutionType = $("#institutionTypeSelect option:selected").val();
        data.institutionType = institutionType;

        //异常类别
        var status = $("#statusSelect option:selected").val();
        data.status = status;

        //异常类别
        var msgId = $("#msgIdSelect option:selected").val();
        data.msgId = msgId;

        return data;
    }

    // 收集页面查询参数
    function getParams(){

        var data = {};

        // 标本日期 from - to
        var $dtFrom = $('#dtFrom');
        var $dtTo = $('#dtTo');

        if ( !$dtFrom.val().length ){
            WeKnow.errorMsg('请输入查询开始日期');
            $dtFrom.focus();
            return false;
        }

        var dtFrom = $dtFrom.val();
        if ( !MY_VALIDATOR.isDate(dtFrom,'yyyy-MM-dd')){
            WeKnow.errorMsg('查询开始日期格式不正确');
            $dtFrom.focus();
            return false;
        }
        data.dtFrom = dtFrom;

        // 查询日期to

        if ( !$dtTo.val().length ){
            WeKnow.errorMsg('请输入查询结束日期');
            $dtTo.focus();
            return false;
        }

        var dtTo = $dtTo.val();
        if ( !MY_VALIDATOR.isDate(dtTo,'yyyy-MM-dd')){
            WeKnow.errorMsg('查询结束日期格式不正确');
            $dtTo.focus();
            return false;
        }
        if($dtFrom.val()>$dtTo.val()){
            WeKnow.errorMsg('开始时间不能大于结束时间');
            return false;
        }
        data.dtTo = dtTo;

        // 登记状态
        var registryStatus =  $('#registryStatus').val();
        data.registryStatus = registryStatus;
        // 诊所名
        var institutionName = $.trim( $('input[name="institutionName"]').val());
        if ( institutionName.length ){
            data.institutionName = institutionName;
        }

        // 地区ID
        var townId =  $('#townId').val();
        if ( townId.length ){
            data.townId = townId;
        }

        // 处方违规类别
        if ($('#prescriptionType').val()!=9){
            data.msgId = $('#prescriptionType').val();
        }

        if ( $('#onlyShowAppeal').prop('checked') ){
            data.onlyShowAppeal = 1;//只显示
        }

        //机构一级类目
        data.institutionTypeFirst = $('select[name="institutionTypeFirstScreen"]').val();//医疗机构类别

        return data;
    }

    // 收集页面查询参数
    function getDetailParams(){

        var data = {};

        // 标本日期 from - to
        var $dtFrom = $('#dtFrom');
        if ( !$dtFrom.val().length ){
            WeKnow.errorMsg('请输入查询开始日期');
            $dtFrom.focus();
            return false;
        }

        var dtFrom = $dtFrom.val();
        if ( !MY_VALIDATOR.isDate(dtFrom,'yyyy-MM-dd')){
            WeKnow.errorMsg('查询开始日期格式不正确');
            $dtFrom.focus();
            return false;
        }
        data.dtFrom = dtFrom;

        // 查询日期to
        var $dtTo = $('#dtTo');
        if ( !$dtTo.val().length ){
            WeKnow.errorMsg('请输入查询结束日期');
            $dtTo.focus();
            return false;
        }

        var dtTo = $dtTo.val();
        if ( !MY_VALIDATOR.isDate(dtTo,'yyyy-MM-dd')){
            WeKnow.errorMsg('查询结束日期格式不正确');
            $dtTo.focus();
            return false;
        }
        if($dtFrom.val()>$dtTo.val()){
            WeKnow.errorMsg('开始时间不能大于结束时间');
            return false;
        }
        data.dtTo = dtTo;
        // 处方违规类别
        if ($('#msgId').val()!=9){
            data.msgId = $('#msgId').val();
        }
        // 状态
        if ($('#checkSt').val()!=9){
            data.checkSt = $('#checkSt').val();
        }

        data.institutionId = $('#institutionId').val();

        return data;
    }

    function initMain() {

        //添加按钮
        var demo = document.getElementById("demo");
        demo.innerHTML += '<script type="text/html" id="barDemo">' +
            ' <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="appeal" > 处理 ' + '</a>' +
            ' <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="prescription" >查看处方' + '</a>' +
            ' <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="picture" >查看图片' + '</a>' +
            '</' + 'script>';

        $(".my_date_control" ).datepicker({
            changeMonth: true,
            changeYear: true,
            dateFormat: 'yy-mm-dd',//日期格式
            yearSuffix: '年', //年的后缀
            showMonthAfterYear:true,//是否把月放在年的后面
            maxDate: (function() {
                return todayTxt;
            })(),//最大日期
            yearRange: (function() {
                // '1990:2010'
                var year1 = '1900';
                var year2 = today.getFullYear();
                return year1 + ':' + year2;
            })(),
            monthNamesShort: ['01','02','03','04','05','06','07','08','09','10','11','12'],
            dayNamesMin: ['日','一','二','三','四','五','六'],
            onUpdatedDatepicker: function(_year, _month, _calendar) {
                // console.log('onUpdatedDatepicker');
                var $c = $('div#ui-datepicker-div');
                $c.find('td[data-handler="selectDay"]').each(function(idx, d) {
                    var $d = $(d);
                    $d.css({'pointer-events': 'auto', 'opacity': 1});
                });
            }
        });

        //查询按钮按下
        $('#search').on('click',function(){
            layui.use('table', function(){
                var table = layui.table;
                //执行一个laypage实例
                checkTable = table.render({
                    elem: '#demo',
                    autoSort: false,
                    initSort: {
                        field: 'violateDt', //排序字段，对应 cols 设定的各字段名
                        type: 'desc' //排序方式  asc: 升序、desc: 降序、null: 默认排序
                    },
                    height: $(document).height() - $('#demo').offset().top - 22,
                    url: "invs_wd_prescription_supervision.do/load",
                    method: "POST",
                    where: getSearchParams(),
                    cellMinWidth: 80,
                    page: true,
                    limit: 10,
                    limits: [10, 20, 50, 100],
                    cols: [[
                        {field:'name', title:'医疗机构', align:'center', width:200, fixed:'left', templet:function (d) {
                                return leftFormat(d.name);
                             }
                        },
                        {field:'violateDt', title:'日期', align:'center', width:120},
                        {field:'title', title:'违规类别', align:'center', width:200, templet:function (d) {
                                return leftFormat(d.title);
                            }
                        },
                        {field:'appealSt', title:'状态', align:'center', width:100,templet:function(d){
                            var appealSt = d.appealSt;
                            if(appealSt == 0 || appealSt == 1 || appealSt == null || appealSt == 11){
                                return '<div style = "text-align:center;color:red">未处理</div>'
                            }else{
                                return '<div style = "text-align:center">已处理</div>'
                            }
                        }},
                        {field:'msgTxt', title:'状态说明', align:'center', width:250, templet:function (d) {
                                return leftFormat(d.msgTxt);
                            }
                        },
                        /*{field:'violateTm', title:'操作时间', align:'center', width:100, templet:function (d) {
                                return datetimeFormat(d.violateTm, 2);
                            }
                        },*/
                        {field:'doctor', title:'违规人员', align:'center', width:100},
                        {field:'appealSt', title:'申诉状态', align:'center', width:100, templet:function (d) {
                                var appealSt = d.appealSt;
                                if (appealSt == null || appealSt == 0 || appealSt == 11) {
                                    return  '未申诉';
                                } else {
                                    return '有申诉'
                                }
                            }
                        },
                        {field:'appeal', title:'申诉内容', align:'center', width:200, templet:function (d) {
                                return leftFormat(d.appeal);
                            }
                        },
                        {field:'appealSt', title:'处理结果', align:'center', width:100, templet:function (d) {
                                var appealSt = d.appealSt;
                                if (appealSt == -1) {
                                    return  '被驳回';
                                } else if (appealSt == 2){
                                    return '无违规';
                                } else {
                                    return leftFormat('');
                                }
                            }
                        },
                        {field:'feedback', title:'处理意见', align:'center', width:200, templet:function (d) {
                                return leftFormat(d.feedback);
                            }
                        },
                        {field:'supervisorName', title:'处理人', align:'center', width:100},
                        {field:'operator', title:'操作', align:'center',  templet:function(d){

                            var html  ='<div class="layui-btn-group" style="display: flex; flex-direction: column; width: 50px">';
                            if ( d.appealSt == 1){
                                html +=  ' <button type="button" class="layui-btn layui-btn-normal layui-btn-xs layuiTool" lay-event="appeal">处理</' + 'button>' ;
                            } else if ( d.appealSt == 0 ) {
                                html +=  ' <button type="button" class="layui-btn layui-btn-normal layui-btn-xs layuiTool" lay-event="appeal">处理</' + 'button>' ;
                            }
                            html += ' <button type="button" class="layui-btn layui-btn-normal layui-btn-xs layuiTool" lay-event="prescription">处方</' + 'button>' ;
                            if(d.appealAtta){
                                html += ' <button type="button" class="layui-btn layui-btn-normal layui-btn-xs layuiTool" lay-event="picture">图片</' + 'button>';
                            }
                            html+='</div>';
                            return html ;
                        }},
                    ]],
                    done: function(res, curr, count){
                        $(".layui-table-main  tr").each(function (index ,val) {
                            $($(".layui-table-fixed .layui-table-body tbody tr")[index]).height($(val).height());
                        });
                    }
                });

                table.on('sort(test)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
                    //尽管我们的 table 自带排序功能，但并没有请求服务端。
                    //有些时候，你可能需要根据当前排序的字段，重新向服务端发送请求，从而实现服务端排序，如：
                    table.reload('demo', {
                        initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。 layui 2.1.1 新增参数
                        ,where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                            field: obj.field //排序字段
                            ,order: obj.type //排序方式
                        }
                    });
                });

                //监听行工具事件
                table.on('tool(test)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
                    var data = obj.data //获得当前行数据
                        ,layEvent = obj.event; //获得 lay-event 对应的值
                    console.log(layEvent);
                    console.log(data);
                    if(layEvent === 'detail'){
                        // $('#institutionId').val(data.pid);
                        // $('#institution_name_dis').text(data.name);
                        // $('#year_month').text('（' + $('#dtFrom').val() + ' 至 ' + $('#dtTo').val() + '）');
                        // $('.toggle-input').toggle();
                        // // 第一个tab显示
                        // $('.div_tab_panel :visible:first').click();
                    }else if(layEvent == 'prescription'){ //查看处方
                        prescription(data);
                    }else if(layEvent == 'picture'){ //查看图片
                        picture(data);
                    }else if(layEvent == 'appeal'){//处理
                        appeal(data);
                    }
                });
            });
        });

        $("button#search").trigger("click");
    }

    function leftFormat(data) {
        if (data == undefined || data == null || $.trim(data).length == 0)  {
            data = '-';
            return '<div style = "text-align:center">' + data + '</div>'
        }
        return '<div style = "text-align:left">' + data + '</div>'
    }

    function datetimeFormat(v, type){
        var date = new Date(v);

        var str = '';
        if (type == 1) {
            var y = date.getFullYear();
            var m = date.getMonth()+1;
            m = m<10?'0'+m:m;
            var d = date.getDate();
            d = d<10?("0"+d):d;
        } else if(type == 2) {
            var h = date.getHours();
            h = h<10?("0"+h):h;
            var M = date.getMinutes();
            M = M<10?("0"+M):M;
            var s = date.getSeconds();
            s = s<10?("0"+s):s;
            str = h+":"+M+":"+s;
        }

        return str;
    }

    /**
     * 处方查看（打印）
     */
    function prescription(data){
		
		WeKnow.loading();

		$.ajax({ 
	        type: "POST", 
	        url: "invs_prescription_violate.do/show_prescription", 
	        data: {violateId:data.violateId,institutionId:data.cid},
	        async: true,//异步调用
	        success: function(data) {
	        	
	        	WeKnow.closeLoading();
	        	
				if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
	        	
	        	if (data.errcode == 0) {
	        		MY_WEST_PRESCRIPTION.resetPrintBody(data.outpatient);
	        		var keepAttr = ["class", "style"];
	    			var options = {retainAttr: keepAttr};
	    			$('#printDiv').printArea(options);
	        	} else if (data.errcode == -1 ) {
	        		WeKnow.errorMsg( data.errMsg );
	        	} else {
	        		WeKnow.systemMsg('查看处方失败，请重新登录后再试');
	        	}
	        }
		});
    }

    /**
     * 查看图片
     */
    function picture(data){
        // 显示交接单图片
        if(data.appealAtta){
            MY_SHOW_IMG.createShowImgModal(data.cid ,data.appealAtta);
        }else{
            WeKnow.errorMsg( "无图片" );
        }
    }

    /**
     * 处理   处理申诉 OR 取消异常
     * @param {*} data 
     */
    function appeal(data){
        var originBtnName= 'closeIllegal';
        if ( data.appealSt == 1){
            originBtnName= 'check';
            console.log('处理');
        } else if ( data.appealSt == 0 ) {
            originBtnName= 'closeIllegal';
            console.log('取消异常');
        }

	
		var illegalId = data.id;
       
        
		// 更新用模态框
		MY_APPEAL.createModalWin(illegalId, originBtnName,
                function () {
                    checkTable.reload();
                }
            );

    }

    return {
        initMain:initMain,
        getDetailParams:getDetailParams,
    }
})();

$(document).ready(function() {

    MY_WD_PRESCRIPTION_SUPERVISION.initMain();

    var $thead= $('thead#thead-prescription');
    var $tbody= $('tbody#tbody-prescription');// 明细

    $('#tbodyViolateInstitutionList').on('click','button[name="showDetail"]',function(){
        var $that = $(this);
        var $parentTr = $that.closest('tr');
        var institutionId = $parentTr.data('institution_id');
        $('#institutionId').val(institutionId);
        // 机构名
        var institutionName = $parentTr.data('institution_name');
        // $('#institutionName').val(institutionName);
        var prescriptionType=$("#prescriptionType").val();
        $('#msgId option').attr("selected",false);
        $('#msgId option[value='+prescriptionType+']').attr("selected",true);
        var params = MY_WD_PRESCRIPTION_SUPERVISION.getDetailParams();
        if(params) {
            MY_PRESCRIPTION_VIOLATE_COM.loadDetailItem(params, $thead, $tbody);
            // 子页面显示诊所名
            $('#institution_name_dis').text(institutionName + '(' + $('#dtFrom').val() + '-' + $('#dtTo').val() + ')');

            $('.input-toggle').toggle();}
    });

    $('#backToWorkspace').on('click',function(){
        $('.input-toggle').toggle();
    });
    // 下拉框变化时刷新
    $('#msgId,#checkSt').on('change',function(){
        var params = MY_WD_PRESCRIPTION_SUPERVISION.getDetailParams();
        if(params) {
            MY_PRESCRIPTION_VIOLATE_COM.loadDetailItem(params, $thead, $tbody);
        }
    });

    // 下拉框变化时刷新
    $('#prescriptionType').on('change',function(){
        MY_WD_PRESCRIPTION_SUPERVISION.loadItem();
    });

    // 跟进
    $tbody.on('click','button[name="follow_up"]',function(){

        var $that = $(this);
        var $parentTr = $that.closest('tr');

        WeKnow.loading();

        $.ajax({
            type: "POST",
            url: "invs_prescription_violate.do/update",
            data: {violateId:$parentTr.data('violate_id'),institutionId:$parentTr.data('institution_id')},
            async: true,//异步调用
            success: function(data) {

                WeKnow.closeLoading();

                if (!WeKnow.filterAjaxResult(data)) return false; // session过期check

                if (data.errcode == 0) {
                    $parentTr.find('.follow-status').text('已跟进');
                    $parentTr.find('button[name="follow_up"]').remove();//删除跟进按钮
                    WeKnow.successMsg('更新成功');
                } else if (data.errcode == -1 ) {
                    WeKnow.errorMsg( data.errMsg );
                } else {
                    WeKnow.systemMsg('更新失败，请重新登录后再试');
                }
            }
        });
    });

    // 查看处方
    $tbody.on('click','button[name="showPre"]',function(){

        var $that = $(this);
        var $parentTr = $that.closest('tr');

        WeKnow.loading();

        $.ajax({
            type: "POST",
            url: "invs_prescription_violate.do/show_prescription",
            data: {violateId:$parentTr.data('violate_id'),institutionId:$parentTr.data('institution_id')},
            async: true,//异步调用
            success: function(data) {

                WeKnow.closeLoading();

                if (!WeKnow.filterAjaxResult(data)) return false; // session过期check

                if (data.errcode == 0) {
                    MY_WEST_PRESCRIPTION.resetPrintBody(data.outpatient);
                    var keepAttr = ["class", "style"];
                    var options = {retainAttr: keepAttr};
                    $('#printDiv').printArea(options);
                } else if (data.errcode == -1 ) {
                    WeKnow.errorMsg( data.errMsg );
                } else {
                    WeKnow.systemMsg('查看处方失败，请重新登录后再试');
                }
            }
        });
    });

    // 显示申诉图片
    $('#tbody-prescription').on('click','button[name="showAppealAtta"]',function(){
        var $that = $(this);
        var $parentTr = $that.closest('tr');

        var appealAtta = $parentTr.data('appeal_atta');
        var institutionId = $('#institutionId').val();
        // 显示交接单图片
        MY_SHOW_IMG.createShowImgModal(institutionId ,appealAtta);
    });

    // 处理申诉 OR 取消异常   注：申诉处理由于多个页面共用，故提炼成appeal.js
    $('#tbody-prescription').on('click','button[name="closeIllegal"],button[name="check"]',function(){
        var $that = $(this);
        var $parentTr = $that.closest('tr');

        var illegalId = $parentTr.data('illegal_id');
        var originBtnName= $that.prop('name');
        // 更新用模态框
        var params = MY_WD_PRESCRIPTION_SUPERVISION.getDetailParams();
        if(params) {
            MY_APPEAL.createModalWin
            (illegalId, originBtnName,
                function () {
                    MY_PRESCRIPTION_VIOLATE_COM.loadDetailItem(params, $thead, $tbody);
                }
            );
        }
    });

    // 导出
    $('a#export').on('click',function(){

        var $that = $(this);

        var data = {};
        data.startDt = new Date().format("yyyy-MM-dd");
        data.endDt = data.startDt;

        var url = WeKnow.getRealPath() + '/invs_prescription_violate.do/output';

        WeKnow.loading();
        $.fileDownload(url,
            {
                httpMethod: 'POST',
                data: data,
                prepareCallback:function(url){
                    console.log('download start')
                    WeKnow.loading();
                },
                successCallback:function(url){
                    console.log('download end')
                    WeKnow.closeLoading();
                },
                failCallback: function (html, url) {
                    WeKnow.errorMsg('下载失败');
                }
            });
    });

});